package com.research.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.api.ApprovalApi;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.bean.BizProcessMessages;
import com.flowable.domain.instance.BpmApprovalDetailReqVO;
import com.flowable.domain.vo.FlowQueryVo;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import com.framework.web.service.PermissionService;
import com.framework.web.service.SysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.common.annotation.Log;
import com.common.core.controller.BaseController;
import com.common.core.domain.AjaxResult;
import com.common.enums.BusinessType;
import com.research.domain.entity.ResearchUnit;
import com.research.service.IResearchUnitService;
import com.common.utils.poi.ExcelUtil;
import com.common.core.page.TableDataInfo;

/**
 * 科研平台-研究机构Controller
 *
 * @author hst
 * @date 2025-03-05
 */
@RestController
@RequestMapping("/research/unit")
@Api(tags = "_科研平台-研究机构")
public class ResearchUnitController extends BaseController
{
    @Autowired
    private ApprovalApi approvalApi;

    @Autowired
    private IResearchUnitService researchUnitService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private IFlowTaskService flowTaskService;

    /**
     * 查询科研平台-研究机构列表
     */
    @PreAuthorize("@ss.hasPermi('research:unit:list')")
    @ApiOperation(value = "查询科研平台-研究机构列表")
    @GetMapping("/list")
    public TableDataInfo list(ResearchUnit researchUnit)
    {
        //科研秘书只能看到挂靠单位在他管理范围内的机构
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if ("biz_kyms".equals(currentRoleKey) ) {
            Map<String, Object> map = researchUnit.getParams();
            map.put("unitAdminScopeReal", SecurityUtils.getLoginUser().getUser().getUnitAdminScopeReal());
        } else if("biz_kyry".equals(currentRoleKey)) {
            Map<String, Object> map = researchUnit.getParams();
            map.put("curKyryPersonId", SecurityUtils.getLoginUser().getUser().getUserRealId());
        }
        startPage();
        List<ResearchUnit> list = researchUnitService.selectResearchUnitList(researchUnit);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('research:unit:list')")
    @GetMapping("/getCheckStatusCount")
    public AjaxResult selectCheckStatusCount(ResearchUnit researchUnit)
    {
        //科研秘书只能看到挂靠单位在他管理范围内的机构
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if ("biz_kyms".equals(currentRoleKey) ) {
            Map<String, Object> map = researchUnit.getParams();
            map.put("unitAdminScopeReal", SecurityUtils.getLoginUser().getUser().getUnitAdminScopeReal());
        } else if("biz_kyry".equals(currentRoleKey)) {
            Map<String, Object> map = researchUnit.getParams();
            map.put("curKyryPersonId", SecurityUtils.getLoginUser().getUser().getUserRealId());
        }
        researchUnit.setCheckStatus(null);
        HashMap<String, Integer> map = researchUnitService.selectCheckStatusCount(researchUnit);
        return success(map);
    }

    /**
     * 导出科研平台-研究机构列表
     */
    @PreAuthorize("@ss.hasPermi('research:unit:export')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResearchUnit researchUnit)
    {
        List<ResearchUnit> list = researchUnitService.selectResearchUnitList(researchUnit);
        ExcelUtil<ResearchUnit> util = new ExcelUtil<ResearchUnit>(ResearchUnit.class);
        util.exportExcel(response, list, "科研平台-研究机构数据");
    }

    /**
     * 获取科研平台-研究机构详细信息
     */
    @PreAuthorize("@ss.hasPermi('research:unit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(researchUnitService.selectResearchUnitById(id));
    }

    /**
     * 新增科研平台-研究机构
     */
    @PreAuthorize("@ss.hasPermi('research:unit:add')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResearchUnit researchUnit)
    {
        String cs = researchUnit.getCheckStatus();
        if (!StringUtils.isEmpty(cs)) {
            return AjaxResult.error("当前的审批状态无法进行此操作！");
        }
        researchUnit.setCheckStatus("-1");
        return toAjax(researchUnitService.insertResearchUnit(researchUnit));
    }

    /**
     * 修改科研平台-研究机构
     */
    @PreAuthorize("@ss.hasPermi('research:unit:edit')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResearchUnit researchUnit)
    {
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        String cs = researchUnit.getCheckStatus();
        if(StringUtils.isEmpty(cs)){
            return AjaxResult.error("当前数据的审批状态异常！");
        }

        if(cs.equals("3")) {
            researchUnit.setCheckStatus("-1");
            researchUnit.setCheckDate("");
            researchUnit.setChecker("");
            researchUnit.setProcessInstanceId("");
        } else if ((cs.equals("1") || cs.equals("2")) && !"biz_kycgly".equals(currentRoleKey)) {
            return AjaxResult.error("当前的审批状态无法进行此操作！");
        }

        return toAjax(researchUnitService.updateResearchUnit(researchUnit));
    }

    @PreAuthorize("@ss.hasPermi('research:unit:edit')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.UPDATE)
    @PutMapping("/editPlatformSummary")
    public AjaxResult editPlatformSummary(@RequestBody ResearchUnit researchUnit)
    {
        ResearchUnit researchUnitNew = new ResearchUnit();
        researchUnitNew.setId(researchUnit.getId());
        researchUnitNew.setPlatformSummary(researchUnit.getPlatformSummary());
        return toAjax(researchUnitService.updateResearchUnit(researchUnitNew));
    }

    /**
     * 删除科研平台-研究机构
     */
    @PreAuthorize("@ss.hasPermi('research:unit:remove')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
//        if ((cs.equals("1") || cs.equals("2")) && !"biz_kycgly".equals(currentRoleKey)) {return AjaxResult.error("当前的审批状态无法进行此操作！");}
        return toAjax(researchUnitService.deleteResearchUnitByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('research:unit:add')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.INSERT)
    @PostMapping("/addStartWorkflow")
    public AjaxResult addStartWorkflow(@RequestBody ResearchUnit researchUnit)
    {
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if ("biz_kyms".equals(currentRoleKey) && StringUtils.isEmpty(researchUnit.getId())) {
            int res = researchUnitService.insertResearchUnit(researchUnit);
            if (res > 0) {
                String processInstanceId = approvalApi.businessEntryApproval(researchUnit.getId(), "科研平台");
                if (StringUtils.isEmpty(processInstanceId)) {
                    return AjaxResult.success("保存成功，但流程发起失败！");        //warn不能正确关闭弹窗
                }
                return toAjax(res);
            }
        }
        return toAjax(0);
    }

    @PreAuthorize("@ss.hasPermi('research:unit:check')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.INSERT)
    @PostMapping("/addAndPass")
    public AjaxResult addAndPass(@RequestBody ResearchUnit researchUnit)
    {
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if ("biz_kycgly".equals(currentRoleKey) && StringUtils.isEmpty(researchUnit.getId()))  {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-dd-MM HH:mm:ss");
            String formattedDateTime = now.format(formatter);
            researchUnit.setChecker(SecurityUtils.getLoginUser().getUser().getNickName());
            researchUnit.setCheckDate(formattedDateTime);
            researchUnit.setCheckStatus("2");
            researchUnit.setProcessInstanceId("0");
            int res = researchUnitService.insertResearchUnit(researchUnit);
            return toAjax(res);
        }
        return toAjax(0);
    }

    @PreAuthorize("@ss.hasPermi('research:unit:edit')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.UPDATE)
    @PutMapping("/editStartWorkflow")
    public AjaxResult editStartWorkflow(@RequestBody ResearchUnit researchUnit)
    {
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if ("biz_kyms".equals(currentRoleKey) && !StringUtils.isEmpty(researchUnit.getId())){
            String cs = researchUnit.getCheckStatus();
            switch ( cs) {
                case "-1":
                case "3":
                    int res = researchUnitService.updateResearchUnit(researchUnit);
                    if (res > 0) {
                        String processInstanceId = approvalApi.businessEntryApproval(researchUnit.getId(), "科研平台");
                        if (StringUtils.isEmpty(processInstanceId)) {
                            return AjaxResult.success("保存成功，但流程发起失败！");        //warn不能正确关闭弹窗
                        }
                        return toAjax(res);
                    }
                    break;
                case "1":
                case "2":
                default:
                    return AjaxResult.error("当前的审批状态无法进行此操作！");
            }
        }
        return toAjax(0);
    }

    @PreAuthorize("@ss.hasPermi('research:unit:check')")
    @Log(title = "科研平台-研究机构", businessType = BusinessType.UPDATE)
    @PutMapping("/editAndPass")
    public AjaxResult editAndPass(@RequestBody ResearchUnit researchUnit)
    {
        int res = 0;
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();
        if (("biz_kycgly").equals(currentRoleKey) && !StringUtils.isEmpty(researchUnit.getId())){
            String cs = researchUnit.getCheckStatus();
            switch ( cs) {
                case "-1":
                case "3":
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-dd-MM HH:mm:ss");
                    String formattedDateTime = now.format(formatter);
                    researchUnit.setChecker(SecurityUtils.getLoginUser().getUser().getNickName());
                    researchUnit.setCheckDate(formattedDateTime);
                    researchUnit.setCheckStatus("2");
                    researchUnit.setProcessInstanceId("0");
                    res = researchUnitService.updateResearchUnit(researchUnit);
                    return toAjax(res);
                case "1":
                    res = researchUnitService.updateResearchUnit(researchUnit);
                    if (res > 0) {
//                      FlowQueryVo fq = new FlowQueryVo();
//                      fq.setProcessDefinitionKey("flow_no4hkh7e");
//                      Map<String,String> map = flowTaskService.todoListBydefKey_Api(fq);
//                      String taskId = map.get(researchUnit.getProcessInstanceId());
//                      BpmTaskApproveReqVO bpmTaskApproveReqVO = new BpmTaskApproveReqVO();
//                      bpmTaskApproveReqVO.setId(taskId);
//                      flowTaskService.approveTask(SecurityUtils.getLoginUser().getUser().getUserId(), bpmTaskApproveReqVO);
                        BpmApprovalDetailReqVO bpmApprovalDetailReqVO = new BpmApprovalDetailReqVO();
                        bpmApprovalDetailReqVO.setProcessInstanceId(researchUnit.getProcessInstanceId());
                        flowTaskService.completeTask(bpmApprovalDetailReqVO);

                        return toAjax(res);
                    }
                    break;
                case "2":
                default:
                    return AjaxResult.error("当前的审批状态无法进行此操作！");
            }
        }
        return toAjax(res);
    }

//    @PreAuthorize("@ss.hasPermi('research:unit:edit')")
//    @Log(title = "科研平台-研究机构", businessType = BusinessType.UPDATE)
//    @PostMapping("/revoke")
//    public AjaxResult revoke(@PathVariable String id)
//    {
//        //本人撤销
//        return toAjax(0);
//    }

    //项目、成果、获奖组件跳转
}
